package com.lujianfei.httprequest.intercepter;

import android.util.Log;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LogIntercepter implements Interceptor {

    private static String TAG = "LogIntercepter==";
    private long startTime;
    private long endTime;
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        endTime = System.currentTimeMillis();
        getRequestInfo(request);
        getResponseInfo(response);
        return response;
    }

    /**
     * 打印请求消息
     * @param request 请求的对象
     */
    private String getRequestInfo(Request request) {
        String str = "";
        if (request == null) {
            return str;
        }
        Log.d(TAG,String.format("->\n%s -> %s cost %s ms",request.method(),request.url().toString(),(endTime-startTime)));
        Log.d(TAG,String.format("->\n=================Headers Begin===============\n\n%s\n=================Headers End=================",request.headers()));
        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return str;
        }
        try {
            Buffer bufferedSink = new Buffer();
            requestBody.writeTo(bufferedSink);
            Charset charset = StandardCharsets.UTF_8;
            str = bufferedSink.readString(charset);
        } catch (Exception e) {
            Log.e(TAG,"" + e);
        }
        Log.d(TAG,String.format("->\n=================Request Body Begin===============\n\n%s\n=================Request Body End=================",str));
        return str;
    }

    /**
     * 打印返回消息
     * @param response 返回的对象
     */
    private String getResponseInfo(Response response) {
        String str = "";
        if (response == null || !response.isSuccessful()) {
            return str;
        }
        ResponseBody responseBody = response.body();
        assert responseBody != null;
        long contentLength = responseBody.contentLength();
        BufferedSource source = responseBody.source();
        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
        } catch (Exception e) {
            Log.e(TAG,"" + e);
        }
        Buffer buffer = source.buffer();
        Charset charset = StandardCharsets.UTF_8;
        if (contentLength != 0) {
            str = buffer.clone().readString(charset);
        }
        Log.d(TAG,String.format("->\n=================Response Begin===============\n\n%s\n=================Response End===================",str));
        return str;
    }
}
